package com.xizi.lotterySystem.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    //单例
    static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper() {
        return mapper;
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            Exception ex = var4;
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    //object 序列化  反序列
    public static String writeValueAsString(Object value) {
        return tryParse(() -> JacksonUtil.getObjectMapper().writeValueAsString(value));
    }

    public static <T> T readValue(String value, Class<T> type) {
        return tryParse(() -> JacksonUtil.getObjectMapper().readValue(value, type));
    }

    //list 反序列化
    public static <T> T readListValue(String value, Class<?> paramClasses) {
        JavaType type = JacksonUtil.getObjectMapper().getTypeFactory().constructParametricType(List.class, paramClasses);
        return tryParse(() -> JacksonUtil.getObjectMapper().readValue(value, type));
    }

}
